<?php
/**
 * Created by PhpStorm.
 * User: lee
 * Date: 2018/1/9
 * Time: 下午3:39
 */

namespace Biz\model;

use Biz\cache\GoodsExtendInfo as cGoodsExtendInfo;
use Biz\pockets\constInterface\CategoryExtendInfo;
use Biz\validate\GoodsExtendInfo as vGoodsExtendInfo;
use Doraemon\model\admTag;
use Doraemon\service\Videos\Videos as sVideos;
use Doraemon\tools\ImgUrl as toolImgUrl;
use Medoo\Medoo;

class GoodsExtendInfo extends \Doraemon\pockets\datebase\BaseDbModel implements CategoryExtendInfo
{
    const _CONFIG_FILE_ = 'db_shop';

    const _CONFIG_SELECT_ = 'db_shop';

    const _DATABASE_ = 'shop';

    const _TABLE_NAME = 'goods_extend_info';


    //配送时间类别
    const SHIPPING_TIME_TYPE_SPOT = 1;//现货
    const SHIPPING_TIME_TYPE_PRE_SALE = 2;//预售

    const SHIPPING_TIME_TYPE_DESC = [
        self::SHIPPING_TIME_TYPE_SPOT => '现货',
        self::SHIPPING_TIME_TYPE_PRE_SALE => '预售',
    ];

    public static $shippingTimeTypeDesc = [
        self::SHIPPING_TIME_TYPE_SPOT => '现货',
        self::SHIPPING_TIME_TYPE_PRE_SALE => '预售',
    ];


    //发货时间
    public static $shippingTimeList = [
        self::SHIPPING_TIME_TYPE_SPOT => [
            '24',
            '48',
            '72',
            '96',
            '120',
            '144'
        ]
    ];

    //定义内容字段里的字段类型值
    const CONTENT_TYPE_IMG = '1';//图片
    const CONTENT_TYPE_TEXT = '2';//文字

    //允许通过createOrEdit操作的字段列表，进行输入转换
    protected static $fields = [
        'is_bywiki',
        'shipping_templ_id',
        'shipping_time_type',
        'shipping_time',
        'spec_cover',
        'spec_video',
        'images_content',
        'style_content',
        'inspection_report',
        'material_content',
        'mounting_method',
        'content',
        'remark',
    ];

//	const PRICE_DESC_IOS = "http://img.hhz1.cn/Op-imageShow/ce18e30v90no00000p8tg6j?iv=1";
//	const PRICE_DESC_ANDRO = "http://img.hhz1.cn/Op-imageShow/76bbb30u00l900000p8tg6j?iv=1";
//
//	const PRICE_DESC_MAP = [
//		1 => self::PRICE_DESC_IOS,
//		2 => self::PRICE_DESC_ANDRO,
//	];


    //保存商品附加信息
    public static function createOrEdit($uid, $goodsId, $data, $scenes = null, $method = null)
    {
        try {

            if (is_null($method)) {

                $has = self::has_master(Medoo::raw(' where goods_id=:goodsId for update', [':goodsId' => $goodsId]));


                $method = $has ? 'update' : 'insert';
            }

            if (!is_null($scenes)) {
                //提交字段进行校验
                if (!vGoodsExtendInfo::validate($data, $scenes)) {

                    $msg = vGoodsExtendInfo::firstError();

                    throw new \Exception($msg);
                }
            }

            $data = self::buidData($data);

            $data['material_content'] = !is_null($data['material_content']) ? json_encode($data['material_content'],
                JSON_UNESCAPED_UNICODE) : '';


            switch ($method) {
                case 'insert':
                    $data['shop_id'] = $uid;
                    $data['goods_id'] = $goodsId;
                    $data['uid'] = $uid;
                    $data['style_content'] = !is_null($data['style_content']) ? $data['style_content'] : '';
                    $data['addtime'] = date('Y-m-d H:i:s');

                    $ret = self::insert($data);
                    break;
                case 'update':
                    $ret = self::update($data, ['goods_id' => $goodsId]);
                    cGoodsExtendInfo::mDelItems($goodsId);
                    break;
            }

            if ($ret->errorCode() !== '00000') {
                throw new \Exception('操作失败,请重试');
            }

            return $goodsId;

        } catch (\Exception $e) {


            throw $e;
        }
    }

    public static function getInfo($goodsId, $needFormat = true)
    {
        $info = self::get([
            'content',
            'shipping_templ_id',
            'shipping_time_type',
            'shipping_time',
            'spec_cover',
            'spec_video',
            'images_content',
            'style_content',
            'material_content',
            'mounting_method',
            'remark',
            'inspection_report'
        ], ['goods_id' => $goodsId]);

        if ($needFormat) {
            self::formatInfo($info);
        }

        return $info;
    }

    public static function getInfoList($goodsId, $needFormat = true)
    {
        $result = self::select([
            'goods_id',
            'content',
            'shipping_templ_id',
            'shipping_time_type',
            'shipping_time',
            'images_content',
            'style_content',
            'material_content',
            'remark',
            'inspection_report'
        ], ['goods_id' => $goodsId]);
        $list = [];
        foreach ($result as $row) {
            if ($needFormat) {
                self::formatInfo($row);
            }
            $list[$row['goods_id']] = $row;
        }
        return $list;
    }

    public static function formatInfo(&$info)
    {
        if (empty($info)) {
            return;
        }

        foreach ($info as $key => &$value) {
            switch ($key) {
                case 'shipping_time_type':
                    $info['shipping_time_type_desc'] = self::$shippingTimeTypeDesc[$value];
                    break;
                case 'images_content':
                    if (!empty($value)) {
                        $value = json_decode($value, true);

                        $value = array_map(function ($v) {
                            $data = [
                                'hash' => $v,
                                'url' => toolImgUrl::getUrl(toolImgUrl::APPTYPE_BIZ, $v,
                                    toolImgUrl::IMAGE_SIZE_ORI_NPHONE),
                            ];

                            return $data;
                        }, $value);
                    }
                    break;
                case 'style_content':
                    $info['style_content_desc'] = isset($info['style_content']) ? admTag::getsTagBysIds($info['style_content']) : [];
                    break;
                case 'material_content':
                    $info['material_content'] = isset($info['material_content']) ? json_decode($info['material_content'],
                        true) : [];
                    break;
                case 'content':
                    if (!empty($value)) {
                        $value = json_decode($value, true);

                        $value = array_map(function ($v) {
                            if ($v['type'] == self::CONTENT_TYPE_IMG && isset($v['img_url'])) {
                                $v['img_url_path'] = toolImgUrl::getUrl(toolImgUrl::APPTYPE_BIZ, $v['img_url'],
                                    toolImgUrl::IMAGE_SIZE_ORI_NPHONE);
                            }

                            return $v;
                        }, $value);

                        $value = json_encode($value, JSON_UNESCAPED_UNICODE);
                    }
                    break;
                case 'inspection_report':
                    if (!empty($value)) {
                        $value = json_decode($value, true);

                        $value = array_map(function ($v) {
                            $data = [
                                'hash' => $v,
                                'url' => toolImgUrl::getUrl(toolImgUrl::APPTYPE_BIZ, $v,
                                    toolImgUrl::IMAGE_SIZE_ORI_NPHONE),
                            ];

                            return $data;
                        }, $value);

                    }
                    break;
                case 'spec_cover':
                    if (!empty($value)) {
                        $value = [
                            'hash' => $value,
                            'url' => toolImgUrl::getUrl(toolImgUrl::APPTYPE_BIZ, $value,
                                toolImgUrl::IMAGE_SIZE_ORI_NPHONE),
                        ];
                    }
                    break;
                case 'spec_video':
                    if (!empty($value)) {
                        $value = [
                            'hash' => $value,
                            'url' => sVideos::getVideoUrlById($value),
                        ];
                    }
                    break;
            }
        }
    }

    public static function getGoodsIdsByShippingTemplId($templId)
    {
        $result = self::select(['goods_id'], ['shipping_templ_id' => $templId]);
        $goodsIds = array_column($result, 'goods_id');
        return $goodsIds;
    }


    public static function checkGoodsByWiki($goodsId)
    {
        $info = self::getInfo($goodsId, false);

        if ($info['is_bywiki'] > 0) {
            return true;
        }
        return false;
    }

    public static function getExtendInfosByGoodsIds($goodsIds)
    {
        $goodsExtends = self::select("*", [
            'goods_id' => $goodsIds
        ]);
        $formatData = [];
        foreach ($goodsExtends as $goodsExtend) {
            $formatData[$goodsExtend['goods_id']] = $goodsExtend;
        }
        return $formatData;
    }

    public static function getExtendInfosByGid($goodsIds)
    {
        $goodsExtends = self::select("*", [
            'goods_id' => $goodsIds
        ]);
        $formatData = [];
        foreach ($goodsExtends as $goodsExtend) {
            self::formatInfo($goodsExtend);
            $formatData[$goodsExtend['goods_id']] = $goodsExtend;
            $formatData[$goodsExtend['goods_id']]['shipping_info'] = [
                'type' => $goodsExtend['shipping_time_type'],
                'shipping_time' => self::getShippingTimeUnit($goodsExtend['shipping_time_type'], $goodsExtend['shipping_time']),
            ];
            $goodsDetail = json_decode($goodsExtend['content'], true) ?: [];
            foreach ($goodsDetail as $detail) {
                if ($detail['type'] == self::CONTENT_TYPE_IMG && isset($detail['img_url_path']) && $detail['img_url_path']) {
                    $formatData[$goodsExtend['goods_id']]['goods_detail'][] = [
                        'type' => self::CONTENT_TYPE_IMG,
                        'img_url' => $detail['img_url_path']
                    ];
                } elseif ($detail['type'] == self::CONTENT_TYPE_TEXT) {
                    $formatData[$goodsExtend['goods_id']]['goods_detail'][] = $detail;
                }
            }

            if ($goodsExtend['inspection_report']) {
                $inspectionReports = $goodsExtend['inspection_report'];
                foreach ($inspectionReports as $inspectionReport) {
                    $formatData[$goodsExtend['goods_id']]['goods_detail'][] = [
                        "type" => self::CONTENT_TYPE_IMG,
                        'img_url' => $inspectionReport['url']
                    ];
                }
            }

            $formatData[$goodsExtend['goods_id']]['spec_cover'] = isset($goodsExtend['spec_cover']['url']) ? $goodsExtend['spec_cover']['url'] : '';
            $formatData[$goodsExtend['goods_id']]['spec_video'] = isset($goodsExtend['spec_video']['url']) ? $goodsExtend['spec_video']['url'] : '';

        }

        return $formatData;
    }


    public static function getRemarksAndShippingTempl($goodsIds)
    {
        $remarks = self::select(['remark', 'goods_id', 'shipping_templ_id', 'tags_content'], ['goods_id' => $goodsIds]);
        $result = [];
        foreach ($remarks as $row) {
            $result[$row['goods_id']]['remark'] = $row['remark'];
            $result[$row['goods_id']]['shipping_templ_id'] = $row['shipping_templ_id'];
            $result[$row['goods_id']]['tags_content'] = $row['tags_content'];
        }
        return $result;
    }

    public static function getGoodsIdByTag($tag)
    {
        return self::select('goods_id', ['tags_content[~]' => $tag]);
    }

    public static function multiSaveShippingTime($goodsIds, $shippingType, $shippingTime)
    {
        if (!vGoodsExtendInfo::validate(['shipping_time_type' => $shippingType, 'shipping_time' => $shippingTime], 'saveshippingtime')) {
            throw new \Exception(vGoodsExtendInfo::firstError());
        }
        return self::update([
            'shipping_time_type' => $shippingType,
            'shipping_time' => $shippingTime
        ], ['goods_id' => $goodsIds])->rowCount();
    }

    public static function getShippingTimeUnit($shippingType, $shippingTime)
    {
        $unit = '小时';
        if ($shippingType == self::SHIPPING_TIME_TYPE_SPOT) {//现货 24，48，72小时，4，5，6天（小于7天,96,120,144小时）
            if (in_array($shippingTime, [96, 120, 144])) {
                $unit = '天';
                $shippingTime = $shippingTime / 24;
            }
        } else if ($shippingType == self::SHIPPING_TIME_TYPE_PRE_SALE) {//非现货(大于7天)
            $unit = '天';
        }
        return $shippingTime . $unit;
    }

    public static function getShippingTimeOfSave($shippingType, $shippingTime)
    {
        if ($shippingType == self::SHIPPING_TIME_TYPE_SPOT) {//现货 24，48，72小时，4，5，6天（小于7天）
            if (in_array($shippingTime, [4, 5, 6])) {
                $shippingTime = $shippingTime * 24;
            }
        }
        return $shippingTime;
    }

    public static function getShippingTimeHour($shippingType, $shippingTime)
    {
        $shippingTimeHouse = $shippingTime;
        if ($shippingType == self::SHIPPING_TIME_TYPE_PRE_SALE) {//非现货(大于7天)
            $shippingTimeHouse = $shippingTime * 24;
        }
        return $shippingTimeHouse;
    }

}